package edu.usm.cs.roberge.workers;

import java.util.List;

import javax.swing.SwingWorker;

import edu.usm.cs.roberge.NewsGroup;
import edu.usm.cs.roberge.NewsReaderImpl;
import edu.usm.cs.roberge.NewsReaderModel;
import edu.usm.cs.roberge.NewsReaderImpl.ProgressListener;
import edu.usm.cs.roberge.views.NewsGroupTableModel;

/**
 * SwingWorker that will invoke the LIST command on the {@link NewsReaderImpl}
 * 
 * @author Dave Roberge
 */
public class FetchNewsGroupWorker extends SwingWorker<Void, NewsGroup> {
	
	private final NewsReaderImpl impl;
	protected final NewsGroupTableModel tableModel;
	private final NewsReaderModel dataModel;

	public FetchNewsGroupWorker(NewsReaderImpl impl, NewsReaderModel dataModel, NewsGroupTableModel tableModel) {
		this.impl = impl;
		this.dataModel = dataModel;
		this.tableModel = tableModel;
	}
	
	@Override
	protected Void doInBackground() throws Exception {
		impl.listNewsGroups(new ProgressListener() {
			@Override
			public void onNewsGroupCreated(NewsGroup newsGroup) {
				publish(newsGroup);
			}
		});
		
		return null;
	}

	@Override
	protected void process(List<NewsGroup> chunks) {
		for(NewsGroup ng : chunks) {
			dataModel.addNewsGroup(ng);
		}
		tableModel.fireTableDataChanged();
	}
}
